package cn.autumnorange;

import cn.autumnorange.commons.util.TokenUtil;
import cn.autumnorange.user.entity.Json;
import cn.autumnorange.user.entity.MyGramtedAuthority;
import cn.autumnorange.user.entity.Test;
import cn.autumnorange.user.entity.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启注解 全局权限设置这里没有手动开启url权限控制会失效
@EnableResourceServer
//ResourceServerConfigurerAdapter资源server无法自动跳转
public class AppUserProviderApplication
//        extends ResourceServerConfigurerAdapter
{
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    public static void main(String[] args) {
        SpringApplication.run(AppUserProviderApplication.class, args);
    }

    @Value("${server.port}")
    String port;
    @Value("${local-server}")
    String localServer;
    @Value("${security.oauth2.client.access-token-uri}")
    String accessTokenUri;

    @RequestMapping("/hi")
    public OAuth2AccessToken getToken(String state, String code) {
        OAuth2AccessToken oAuth2AccessToken = TokenUtil.getToken(accessTokenUri, "Basic Y2xpZW50LWE6Y2xpZW50LWE=", code, localServer + "/hi", state);
//        accessTokenUri, "Basic b3JkZXI6b3JkZXI=", code, localServer + "/hi", state
        return oAuth2AccessToken;
    }

    @RequestMapping("/TestJson")
    public Test home(@RequestBody Test test) {
        return test;
    }

    @PreAuthorize("hasRole('ROLE_admin')")
    @RequestMapping("/test1")
    public String test(@RequestParam(value = "name", defaultValue = "forezp") String name) {
        return "hi test11111111 " + name + " ,i am from port:" + port;
    }

    @ResponseBody
    @RequestMapping("/testJson")
    public Json json(@RequestParam(value = "name", defaultValue = "forezp") String name) {
        Json json = new Json(name);

        json.setList(new ArrayList<String>());
        json.getList().add("testJsonList");
        List<MyGramtedAuthority> collection = new ArrayList<MyGramtedAuthority>();
        MyGramtedAuthority grantedAuthority = new MyGramtedAuthority("ROLE_admin");
        collection.add(grantedAuthority);

        json.setAuthorities(collection);

        System.out.println("json resource value:" + ((List) json.getAuthorities()).get(0));
        return json;
    }

//    @Override
//    public void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
//    }

//    public static OAuth2AccessToken getToken(String client_id, String grant_type, String code, String redirect_uri,
//                                             String client_secret, String state) {
////        HttpClient client = new HttpClient();
////  PostMethod postMethod = new PostMethod(url);
//
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//
//        String url = "http://localhost:8888/oauth/token?grant_type="
//                + grant_type + "&code=" + code + "&redirect_uri=" + redirect_uri + "&state" + state;
//
//        HttpPost httpPost = new HttpPost(url);
//        httpPost.addHeader("Authorization", "Basic Y2xpZW50LWE6Y2xpZW50LWE=");
//
//        HttpResponse response = null;
//        try {
//            response = httpClient.execute(httpPost);
//        } catch (ClientProtocolException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        String result = "";
//        if (response.getStatusLine().getStatusCode() == 200) {
//            try {
//
//                result = EntityUtils.toString(response.getEntity(), "UTF-8");
//                // 解析token的json数据
//                JSONObject jsonObject = JSONObject.parseObject(result);
//                DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(jsonObject.getString("access_token"));
////        accessToken.setAccess_token();
//                accessToken.setTokenType(jsonObject.getString("token_type"));
////        accessToken.setToken_type(jsonObject.getString("token_type"));
//                accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(jsonObject.getString("refresh_token")));
////        accessToken.setRefresh_token(jsonObject.getString("refresh_token"));
////        accessToken.setExpires_in(jsonObject.getString("expires_in"));
//                accessToken.setExpiration(new Date(Long.parseLong(jsonObject.getString("expires_in"))));
//                HashSet set = new HashSet();
//                set.add(jsonObject.getString("scope"));
//                accessToken.setScope(set);
//                return accessToken;
//            } catch (ParseException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
}
